
package com.jb.web.util.database;

import com.jb.framework.DataSourceManager;
import com.jb.framework.database.UpdateDBCommand;
import com.jb.web.bean.Page;
import com.jb.web.bean.database.DatabaseTable;
import com.jb.web.bean.event.UIEvent;
import com.jb.web.context.WebContext;

import java.sql.Connection;
import java.sql.SQLException;

public class SqlConsoleEH {
    public void onExecute(WebContext ctx, UIEvent event) {
        String sql = event.getParameter("sqlstatements");
        if(sql==null||sql.length()==0) {
            return;
        }
        Page page = ctx.getPage();
        DatabaseTable tb = (DatabaseTable) page.getDescendantByClientId("sqlTable");
        tb.setVisible("false");
        if(sql.toUpperCase().startsWith("SELECT"))
        {
            tb.setSelectStatement(sql);
            tb.setGenerateBinding(true);
            
            tb.valueChanged(ctx);
            tb.setVisible("true");
        }else {
            UpdateDBCommand command = new UpdateDBCommand(sql);
            Connection conn = null;
            try {
                conn = DataSourceManager.getConnection(this);
                command.execute(conn);
                conn.commit();
            } catch (SQLException e) {
                ctx.addErrorMessage(this, "Failed due to " + e.getMessage());
            }finally
            {
                DataSourceManager.releaseConnection(this, conn);
            }
        }
    }
}
